package com.txsj.scan.presenter;

import android.app.Activity;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.greendao.EpcInfoDao;
import com.txsj.scan.base.BasePresenter;
import com.txsj.scan.bean.BaseListResult;
import com.txsj.scan.bean.EpcGoodsInfo;
import com.txsj.scan.bean.EpcInfo;
import com.txsj.scan.bean.EpcTagBean;
import com.txsj.scan.bean.GoodsInfo;
import com.txsj.scan.bean.LabelBean;
import com.txsj.scan.bean.WarehouseBean;
import com.txsj.scan.db.GreenDaoUtils;
import com.txsj.scan.http.ApiServer;
import com.txsj.scan.http.UrlInterface;
import com.txsj.scan.http.requestframework.RetrofitManager;
import com.txsj.scan.reader.EpcUtils;
import com.txsj.scan.reader.helper.InventoryBuffer;
import com.txsj.scan.utils.GZIPUtils;
import com.txsj.scan.utils.GsonFactory;
import com.txsj.scan.utils.LabelUtils;
import com.txsj.scan.utils.MD5Util;
import com.txsj.scan.utils.PreferenceUtil;
import com.txsj.scan.utils.Trace;
import com.txsj.scan.view.IReadLabelView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.ResponseBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ReadLabelPresenter extends BasePresenter<IReadLabelView> {
    private static final int RETRY_LABEL = 0x141;
    private static final int SCAN_ERROR = 0x143;
    private static final int USEFUL = 0x144;
    private static final int ON_LOADING = 0x147;
    private static final int ON_SUCCESS = 0x148;
    private static final int ON_ERROR = 0x149;

    private int lastPosition = 0;//全局变量，记录上一次遍历到lastListde位置

    // 设置变量
    // 可重试次数
    private int maxConnectCount = 20;
    // 当前已重试次数waitRetryLabelTime
    private int currentRetryGoodsCount = 0;//商品的
    private int currentRetryLabelCount = 0;//标签的
    // 重试等待时间
    private int waitRetryGoodsTime = 0;
    private int waitRetryLabelTime = 0;
    // 当前分页数量
    private int goodsPageIndex = 1;
    private int tagPageIndex = 1;

    private Thread goodsAndTagThread;
    private long time_difference;
    private int epcLimit = 10000;//标签缓存每页加载的条数

    private List<String> EPCList;        //所有扫到的标签集合
    private List<EpcInfo> usefulTagList;     //扫到后匹配成功的标签
    private List<String> unUsefulList;   //没有识别的标签集合
    private List<LabelBean> unUsefulLabelList;   //没有识别的标签及信息集合
    private List<EpcInfo> unKnownList;   //识别成功但没有匹配的标签集合
    private List<EpcGoodsInfo> usefulList; //有用的商品集合

    private List<GoodsInfo> goodsInfoList;//商品列表先选商品带回的所选的商品集合

    public void setGoodsInfoList(List<GoodsInfo> goodsInfoList) {
        this.goodsInfoList = goodsInfoList;
    }

    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case USEFUL:
                    if (null != view)
                        view.onUpdateCount(unUsefulLabelList, unUsefulList, usefulTagList, goodsInfoList.size(),
                                EpcUtils.getM_curInventoryBuffer().lsTagList.size());
                    break;
                case ON_LOADING:
                    if (null != view)
                        view.onLoading();
                    break;
                case ON_ERROR:
                    if (null != view)
                        if (null != msg.obj) {
                            String error = (String) msg.obj;
                            view.onError(error);
                        }
                    break;
                case ON_SUCCESS:
                    if (null != view)
                        view.onSuccess();
                    break;
                case SCAN_ERROR:
                    if (null != view)
                        view.onScanError("未扫描到标签，请重试");
                    break;
                case RETRY_LABEL:
                    getGoodsAndTagHttp();
                    break;

            }
        }
    };

    public ReadLabelPresenter(IReadLabelView view) {
        super(view);
        unUsefulList = new ArrayList<>();
        unUsefulLabelList = new ArrayList<>();
        unKnownList = new ArrayList<>();
        usefulList = new ArrayList<>();
        EPCList = new ArrayList<>();
        usefulTagList = new ArrayList<>();
        goodsInfoList = new ArrayList<>();
    }

    @Override
    protected void initModel() {

    }

    /**
     * 获取标签数据
     * 韩断线重连机制
     */
//    private void getEpcRetrofitHttp() {
//        Map<String, String> params = RetrofitManager.getParams();
//        params.put("brandid", PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID,""));
//        params.put("select_brand", PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID,""));
//        params.put("page_index", tagPageIndex + "");
//        params.put("page_size", "10000");
//        params.put("timeStamp", System.currentTimeMillis() / 1000 + "");//加时间戳参数
//        params.put("sign", MD5Util.md5(params));//md5加密并加参数
////        view.onLoading();
////        if (tagPageIndex == 1) {
//            handler.sendEmptyMessage(ON_LOADING);
////        }
//        time_difference = System.currentTimeMillis();
//        RetrofitManager.getDefault().create(ApiServer.class).getEpcListUrl(RetrofitManager.getHeader(), params)
//                .retryWhen(new Function<Observable<Throwable>, ObservableSource<?>>() {
//                    @Override
//                    public ObservableSource<?> apply(Observable<Throwable> throwableObservable) throws Exception {
//                        return throwableObservable.flatMap(new Function<Throwable, ObservableSource<?>>() {
//                            @Override
//                            public ObservableSource<?> apply(Throwable throwable) throws Exception {
//                                // 输出异常信息
//                                Trace.e("wcj,Tag+++++：" + throwable.toString());
//                                /**
//                                 * 需求1：根据异常类型选择是否重试
//                                 * 即，当发生的异常 = 网络异常 = IO异常 才选择重试
//                                 */
////                                if (throwable instanceof IOException) {
////                                    Trace.e("wcj+++++：" + "属于IO异常，需重试");
//                                /**
//                                 * 需求2：限制重试次数
//                                 * 即，当已重试次数 < 设置的重试次数，才选择重试
//                                 */
//                                if (currentRetryLabelCount < maxConnectCount) {
//                                    // 记录重试次数
//                                    currentRetryLabelCount++;
//                                    Trace.e("wcj,Tag+++++：重复次数" + +currentRetryLabelCount);
//                                    /**
//                                     *  需求2：实现重试
//                                     *  通过返回的Observable发送的事件 = Next事件，从而使得retryWhen（）重订阅，最终实现重试功能
//                                     *  * *
//                                     *  需求3：延迟1段时间再重试
//                                     *  * 采用delay操作符 = 延迟一段时间发送，以实现重试间隔设置
//                                     *  *
//                                     *  * 需求4：遇到的异常越多，时间越长 *
//                                     *  在delay操作符的等待时间内设置 = 每重试1次，增多延迟重试时间1s *
//                                     */
//                                    // 设置等待时间
//                                    waitRetryLabelTime = 1000 + waitRetryLabelTime * 1000;
//                                    Trace.e("wcj,Tag+++++： 等待时间 =" + waitRetryLabelTime);
//                                    return Observable.just(1).delay(waitRetryLabelTime, TimeUnit.MILLISECONDS);
//                                } else {
//                                    // 若重试次数已 > 设置重试次数，则不重试
//                                    // 通过发送error来停止重试（可在观察者的onError（）中获取信息）
//                                    return Observable.error(new Throwable("重试次数已超过设置次数 = " + currentRetryLabelCount + "，即 不再重试"));
//                                }
////                                }
//                                // 若发生的异常不属于I/O异常，则不重试
//                                // 通过返回的Observable发送的事件 = Error事件 实现（可在观察者的onError（）中获取信息）
////                                else {
////                                    return Observable.error(new Throwable("发生了非网络异常（非I/O异常）"));
////                                }
//                            }
//                        });
//                    }
//                })
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.from(Looper.myLooper()))
//                .subscribe(new Observer<BaseListResult<EpcInfo>>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//                        compositeDisposable.add(d);
//                    }
//
//                    @Override
//                    public void onNext(BaseListResult<EpcInfo> baseBean) {
//                        Trace.e("wcj时间差,未压缩的======="+(System.currentTimeMillis()-time_difference));
////                        Trace.e("商品数据： " + baseBean.getData());
//                        if (baseBean.isSuccess()) {
//                            List<EpcInfo> list = baseBean.getData();
//
//                            if (null != list && list.size() > 0) {
//                                EpcInfoDao epcInfoDao = GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao();
//                                for (EpcInfo info : list) {
//                                    epcInfoDao.insertOrReplace(info);
//                                }
//
//
//                                if (list.size() == 10000) {
//                                    tagPageIndex++;
//                                    getEpcRetrofitHttp();
//                                    Trace.e("wcj,Tag+++++++++++++++" + tagPageIndex);
//                                } else {
//                                    //本地记录一个参数，list.size() < 100：加载完毕
//                                    PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.LABEL_IS_LOADED, true);//本地记录加载成功
//                                    PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.FIRST_LOAD_LABEL_AND_GOODS, true);//本地记录加载成功
////                                  view.onClassifySuccess();
//                                    handler.sendEmptyMessage(ON_SUCCESS);
//                                }
//                            } else {
////                                view.onError("暂无商品数据");
////                                Message msg = new Message();
////                                msg.obj = "暂无标签数据数据";
////                                msg.what = ON_ERROR;
////                                handler.sendMessage(msg);
////                                Trace.e("wcj,Tag+++++：" + "数据为空");
//                                //本地记录一个参数，list.size() < 100：加载完毕
//                                PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.LABEL_IS_LOADED, true);//本地记录加载成功
////                                  view.onClassifySuccess();
//                                handler.sendEmptyMessage(ON_SUCCESS);
//                            }
//                        } else {
//                            Message msg = new Message();
//                            msg.obj = "暂无标签数据数据";
//                            msg.what = ON_ERROR;
//                            handler.sendMessage(msg);
//                            Trace.e("wcj,Tag+++++：" + "数据为空");
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
////                        view.onError(e.getMessage());
//                        Message msg = new Message();
//                        msg.obj = e.getMessage();
//                        msg.what = ON_ERROR;
//                        handler.sendMessage(msg);
//                        Trace.e("wcj,Tag+++++：" + e);
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });
//    }

    private int retryLabelCount = 0;//重试次数
    private int reTryLabelMax = 20;//重试最大次数，超过就关闭
    private long reTryLabelDelay = 1500;//重试间隔，1.5s

    /**
     * 获取标签数据
     * 韩断线重连机制
     */
    private void getEpcRetrofitHttp() {
        Map<String, String> params = RetrofitManager.getParams();
        params.put("brandid", PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, ""));
        params.put("select_brand", PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, ""));
        params.put("page_index", tagPageIndex + "");
        params.put("page_size", epcLimit + "");

        Map<String, String> header = RetrofitManager.getHeader();
        header.put("gzip_type", "1");
        Trace.e("wcj：当前线程" + Looper.myLooper());
        handler.sendEmptyMessage(ON_LOADING);

        time_difference = System.currentTimeMillis();
        if (retryLabelCount != 0) {
            Trace.e("重连次数：" + retryLabelCount);
        }
        RetrofitManager.getDefault().create(ApiServer.class).getEpcByteListUrl(header, params)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        Trace.e("wcj时间差,压缩后的=======" + (System.currentTimeMillis() - time_difference));
                        try {
                            if (null != response && null != response.body()) {
                                if (null != response.body().source() && response.isSuccessful()) {
                                    //获得response中的body的字节数组
//                                    byte[] data = response.body().bytes();
                                    //通过UTF-8解压缩成json字符串
                                    String json = GZIPUtils.uncompressToString(response.body().source().readByteArray(), GZIPUtils.GZIP_ENCODE_UTF_8);
                                    //将字符串转换成定义好的数据类型
                                    final JSONObject jsonObject = new JSONObject(json);
                                    time_difference = System.currentTimeMillis();
                                    // 对数据进行操作
                                    new Thread(new Runnable() {
                                        @Override
                                        public void run() {
                                            epcNext(jsonObject);
                                        }
                                    }).start();

                                } else {
                                    // todo 返回的字节数组无数据
                                    if (retryLabelCount < reTryLabelMax) {
                                        retryLabelCount++;
                                        Message msg = new Message();
                                        msg.what = RETRY_LABEL;
                                        handler.sendMessageDelayed(msg, reTryLabelDelay);
                                    } else {
                                        retryLabelCount = 0;//重置
                                        Message msg = new Message();
                                        msg.obj = "网络异常";
                                        msg.what = ON_ERROR;
                                        handler.sendMessage(msg);
                                    }
                                }
                            } else {
                                // TODO 网络异常
                                if (retryLabelCount < reTryLabelMax) {
                                    retryLabelCount++;
                                    Message msg = new Message();
                                    msg.what = RETRY_LABEL;
                                    handler.sendMessageDelayed(msg, reTryLabelDelay);
                                } else {
                                    retryLabelCount = 0;//重置
                                    Message msg = new Message();
                                    msg.obj = "网络异常";
                                    msg.what = ON_ERROR;
                                    handler.sendMessage(msg);
                                }
                            }
                        } catch (IOException e) {
                            e.printStackTrace();
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {
                        Trace.e("wcj,Tag+++++：" + t.getMessage());
                        if (retryLabelCount < reTryLabelMax) {
                            retryLabelCount++;
                            Message msg = new Message();
                            msg.what = RETRY_LABEL;
                            handler.sendMessageDelayed(msg, reTryLabelDelay);
                        } else {
                            retryLabelCount = 0;//重置
                            Message msg = new Message();
                            msg.obj = "网络异常";
                            msg.what = ON_ERROR;
                            handler.sendMessage(msg);
                        }
                    }
                });
    }

    /**
     * 对标签请求流进行解析
     *
     * @param jsonObject
     */
    private void epcNext(JSONObject jsonObject) {
        Trace.i("wcj：" + jsonObject.toString());
        Trace.e("wcj：当前线程" + Looper.myLooper());
        boolean isSuccess = jsonObject.optBoolean("success");
        if (isSuccess) {
            JSONArray jsonArray = jsonObject.optJSONArray("data");
            if (jsonArray.length() == 0) return;
            final List<EpcInfo> list = GsonFactory.getObjectList(jsonArray.toString(), EpcInfo.class);
            if (null != list && list.size() > 0) {
                final EpcInfoDao epcInfoDao = GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao();

                epcInfoDao.getSession().runInTx(new Runnable() {
                    @Override
                    public void run() {
                        epcInfoDao.insertOrReplaceInTx(list);
                    }
                });
                if (list.size() == epcLimit) {
                    tagPageIndex++;
                    getEpcRetrofitHttp();
                    Trace.e("wcj,Tag+++++++++++++++" + tagPageIndex);
                } else {
                    //本地记录一个参数，list.size() < 100：加载完毕
                    PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.LABEL_IS_LOADED, true);//本地记录加载成功
                    handler.sendEmptyMessage(ON_SUCCESS);
                    Trace.e("wcj,Tag++++++++++epc.size:" + GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao().loadAll().size());
                    Trace.e("wcj,Tag++++++++++存库时间差:" + (System.currentTimeMillis() - time_difference));
                }
            } else {
                //本地记录一个参数，list.size() < 100：加载完毕
                PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.LABEL_IS_LOADED, true);//本地记录加载成功
                handler.sendEmptyMessage(ON_SUCCESS);
            }
        } else {
            Message msg = new Message();
            msg.obj = "暂无标签数据数据";
            msg.what = ON_ERROR;
            handler.sendMessage(msg);
            Trace.e("wcj,Tag+++++：" + "数据为空");
        }
    }


    /**
     * 开始对比
     */
    public void scan(boolean isStart) {
        if (isStart) {
            tagHandler.postDelayed(looperTagRunnable, 500);
        } else {
            tagHandler.removeCallbacks(looperTagRunnable);
        }
    }

    Handler tagHandler = new Handler();
    //循环读取标签库
    private Runnable looperTagRunnable = new Runnable() {
        @Override
        public void run() {
            tagHandler.postDelayed(this, 1000);
            selectEpcList();
        }
    };

    /**
     * 获取品牌下所有的商品数据
     * 含有断线重连机制，一直重连
     */
//    private void getGoodsLabel() {
//        Map<String, String> params = new HashMap<>();
//        StringBuilder builder = new StringBuilder();
//        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID,""));
//        builder.append("|");
//        builder.append(PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID,0));
//        builder.append("|");
//        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.TOKEN,""));
//        builder.append("|");
//        builder.append(0);
//        builder.append("|");
//        params.put("brandtoken", builder.toString());
//        params.put("select_brand", PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID,""));
//        params.put("brandid", PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID,""));
//        params.put("page_index", goodsPageIndex + "");
//        params.put("page_size", "10000");
//        params.put("timeStamp", System.currentTimeMillis() / 1000 + "");//加时间戳参数
//        params.put("sign", MD5Util.md5(params));//md5加密并加参数
//
////        view.onLoading();
////        if (goodsPageIndex == 1) {
//            handler.sendEmptyMessage(ON_LOADING);
////        }
//        RetrofitManager.getDefault().create(ApiServer.class).getEpcGoodsListUrl(RetrofitManager.getHeader(), params)
//                .retryWhen(new Function<Observable<Throwable>, ObservableSource<?>>() {
//                    @Override
//                    public ObservableSource<?> apply(Observable<Throwable> throwableObservable) throws Exception {
//                        // 参数Observable<Throwable>中的泛型 = 上游操作符抛出的异常，可通过该条件来判断异常的类型
//                        return throwableObservable.flatMap(new Function<Throwable, ObservableSource<?>>() {
//                            @Override
//                            public ObservableSource<?> apply(Throwable throwable) throws Exception {
//                                // 输出异常信息
//                                Trace.e("wcj:Goods+++++：" + throwable.toString());
//                                /**
//                                 * 需求1：根据异常类型选择是否重试
//                                 * 即，当发生的异常 = 网络异常 = IO异常 才选择重试
//                                 */
////                                if (throwable instanceof IOException) {
////                                    Trace.e("wcj+++++：" + "属于IO异常，需重试");
//                                /**
//                                 * 需求2：限制重试次数
//                                 * 即，当已重试次数 < 设置的重试次数，才选择重试
//                                 */
//                                if (currentRetryGoodsCount < maxConnectCount) {
//                                    // 记录重试次数
//                                    currentRetryGoodsCount++;
//                                    Trace.e("wcj:Goods+++++：重复次数" + +currentRetryGoodsCount);
//                                    /**
//                                     *  需求2：实现重试
//                                     *  通过返回的Observable发送的事件 = Next事件，从而使得retryWhen（）重订阅，最终实现重试功能
//                                     *  * *
//                                     *  需求3：延迟1段时间再重试
//                                     *  * 采用delay操作符 = 延迟一段时间发送，以实现重试间隔设置
//                                     *  *
//                                     *  * 需求4：遇到的异常越多，时间越长 *
//                                     *  在delay操作符的等待时间内设置 = 每重试1次，增多延迟重试时间1s *
//                                     */
//                                    // 设置等待时间
//                                    waitRetryGoodsTime = 1000 + waitRetryGoodsTime * 1000;
//                                    Trace.e("wcj:Goods+++++： 等待时间 =" + waitRetryGoodsTime);
//                                    return Observable.just(1).delay(waitRetryGoodsTime, TimeUnit.MILLISECONDS);
//                                } else {
//                                    // 若重试次数已 > 设置重试次数，则不重试
//                                    // 通过发送error来停止重试（可在观察者的onError（）中获取信息）
//                                    return Observable.error(new Throwable("重试次数已超过设置次数 = " + currentRetryGoodsCount + "，即 不再重试"));
//                                }
////                                }
//                                // 若发生的异常不属于I/O异常，则不重试
//                                // 通过返回的Observable发送的事件 = Error事件 实现（可在观察者的onError（）中获取信息）
////                                else {
////                                    return Observable.error(new Throwable("发生了非网络异常（非I/O异常）"));
////                                }
//                            }
//                        });
//                    }
//                })
//                .subscribeOn(Schedulers.io())
//                .observeOn(AndroidSchedulers.from(Looper.myLooper()))//将回调放入到子线程中，防止主线程的loading框无响应
//                .subscribe(new Observer<BaseListResult<EpcGoodsInfo>>() {
//                    @Override
//                    public void onSubscribe(Disposable d) {
//                        compositeDisposable.add(d);
//                    }
//
//                    @Override
//                    public void onNext(BaseListResult<EpcGoodsInfo> result) {
//                        if (result.isSuccess()) {
//                            List<EpcGoodsInfo> list = result.getData();
//                            if (null != list && list.size() > 0) {
//                                EpcGoodsInfoDao epcGoodsInfoDao = GreenDaoUtils.getSingleTon().getmDaoSession().getEpcGoodsInfoDao();
//                                for (EpcGoodsInfo info : list) {
//                                    epcGoodsInfoDao.insertOrReplace(info);
//                                }
//
//                                if (list.size() == 10000) {
//                                    goodsPageIndex++;
//                                    getGoodsLabel();
//                                    Trace.e("wcj:Goods+++++++++++++++"+ goodsPageIndex);
//                                } else {
//                                    //本地记录一个参数，list.size() < 100：加载完毕
//                                    PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.LABEL_IS_LOADED, true);//本地记录加载成功
//                                    // view.onClassifySuccess();
//                                    handler.sendEmptyMessage(ON_SUCCESS);
//                                }
//                            } else {
////                                view.onError("暂无标签数据");
////                                Message msg = new Message();
////                                msg.obj = "暂无商品数据";
////                                msg.what = ON_ERROR;
////                                handler.sendMessage(msg);
////                                Trace.e("wcj:Goods+++++：" + "数据为空");
//                                //本地记录一个参数，list.size() < 100：加载完毕
//                                PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.LABEL_IS_LOADED, true);//本地记录加载成功
//                                // view.onClassifySuccess();
//                                handler.sendEmptyMessage(ON_SUCCESS);
//                            }
//                        } else {
////                            view.onError("暂无标签数据");
//                            Message msg = new Message();
//                            msg.obj = "暂无商品数据";
//                            msg.what = ON_ERROR;
//                            handler.sendMessage(msg);
//                            Trace.e("wcj:Goods+++++：" + result.getMsg());
//                        }
//                    }
//
//                    @Override
//                    public void onError(Throwable e) {
////                        view.onError(e.getMessage());
//                        Message msg = new Message();
//                        msg.obj = e.getMessage();
//                        msg.what = ON_ERROR;
//                        handler.sendMessage(msg);
//                        Trace.e("wcj:Goods+++++：" + e.getMessage());
//                    }
//
//                    @Override
//                    public void onComplete() {
//
//                    }
//                });
//    }

    /**
     * 筛选标签，返回的是对应标签库里的数据，唯一的（否则标签造重了）
     *
     * @return 对比后的标签，要么有一个，要么没有
     */
    private void selectEpcList() {
        //判断缓冲区及其列表是否为空
        if (null == EpcUtils.getM_curInventoryBuffer() || null == EpcUtils.getM_curInventoryBuffer().lsTagList)
            return;
        if (lastPosition >= EpcUtils.getM_curInventoryBuffer().lsTagList.size() - 1) return;

        for (int i = lastPosition; i < EpcUtils.getM_curInventoryBuffer().lsTagList.size(); i++) {
            lastPosition = i;
            InventoryBuffer.InventoryTagMap map = EpcUtils.getM_curInventoryBuffer().lsTagList.get(i);
            String strEpc = map.strEPC.replaceAll(" ", "");
            //目前捕获一下异常
            try {
                if (TextUtils.isEmpty(strEpc) || strEpc.length() < 24) {
                    Trace.e("非正常的标签");
                    continue;//正常的标签是24位的，不满足二十四位说明是异常标签
                }
                //解析
                String epcCode = strEpc.substring(9, strEpc.length());
                long id = Long.parseLong(epcCode, 16);

                //对比筛选
                List<EpcInfo> epcList = GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao().queryBuilder()
                        .where(EpcInfoDao.Properties.Tag_id.eq(id))
                        .list();
                if (epcList != null && epcList.size() > 0 && epcList.get(0).getGoods_id() != 0) {
                    //将已经识别的TagInfo标签的strEPC设置到标签库中
                    EpcInfo epcInfo = epcList.get(0);
                    epcInfo.setStrEpc(strEpc);


                    //通过标签筛选完成的信息对比商品库筛选
                    selectGoods(epcInfo);
                } else {
                    if (!unUsefulList.contains(strEpc)) {
                        unUsefulList.add(strEpc);
                        LabelBean labelBean = new LabelBean();
                        labelBean.setStrEpc(strEpc);
                        labelBean.setClassId(LabelUtils.getClassId(strEpc));
                        labelBean.setGroupId(LabelUtils.getGroupId(strEpc));
                        labelBean.setSerialGroupId(LabelUtils.getSerialGroupId(strEpc));
                        labelBean.setTotalGroup(LabelUtils.getTotalGroup(strEpc));
                        unUsefulLabelList.add(labelBean);
                    }
                }
            } catch (StringIndexOutOfBoundsException e) {
                Trace.e("异常标签：" + strEpc);
                continue;//标签不规整跳过
            } catch (NumberFormatException e) {
                Trace.e("异常标签：" + strEpc);
                continue;//数据格式化异常
            } catch (Exception e) {
                continue;//标签不规整跳过
            }
        }
        handler.sendEmptyMessage(USEFUL);
    }


    /**
     * 对比找出标签数据后查询对应的商品
     *
     * @param epcInfo
     */
    private void selectGoods(EpcInfo epcInfo) {
//        List<EpcGoodsInfo> goodsInfoList = GreenDaoUtils.getSingleTon().getmDaoSession().getEpcGoodsInfoDao().queryBuilder()
//                .where(EpcGoodsInfoDao.Properties.Goods_id.eq(epcInfo.getGoods_id()))
//                .list();
//        if (null != goodsInfoList && goodsInfoList.size() > 0) {
//            goodsInfoList.get(0).setStrEPCList(epcInfo.getStrEPCList());//将标签里存的标签码集合赋值到商品集合里
//            usefulList.add(goodsInfoList.get(0));
//        } else {
//            unKnownList.add(epcInfo);
//        }

        boolean isContain = false;
        for (int i = 0; i < goodsInfoList.size(); i++) {
            if (epcInfo.getGoods_id() == goodsInfoList.get(i).getGoods_id()) {
//                List<EpcInfo> list = goodsInfoList.get(i).getEpcList();
//                if (null == list){
//                    list = new ArrayList<>();
//                }
//                list.add(epcInfo);
//                goodsInfoList.get(i).setEpcList(list);
                isContain = true;

                usefulTagList.add(epcInfo);
                break;
            }
        }
        if (!isContain) {
            unKnownList.add(epcInfo);
        }
    }

    public void clear() {
        lastPosition = 0;
//        usefulList.clear();
        unKnownList.clear();
        unUsefulList.clear();
        unUsefulLabelList.clear();
        usefulTagList.clear();
        EpcUtils.getInstance((Activity) view.context()).clearTagList();
    }

    /**
     * 在调拨完成后更新
     * 商品库和标签库
     */
    private void refresh() {
        currentRetryGoodsCount = 0;
        currentRetryLabelCount = 0;
        waitRetryGoodsTime = 0;
        waitRetryLabelTime = 0;
        goodsPageIndex = 1;
        tagPageIndex = 1;
        PreferenceUtil.getInstance().commitBoolean(PreferenceUtil.FIRST_LOAD_LABEL_AND_GOODS, true);
        GreenDaoUtils.getSingleTon().getmDaoSession().getEpcGoodsInfoDao().deleteAll();
        GreenDaoUtils.getSingleTon().getmDaoSession().getEpcInfoDao().deleteAll();
        GreenDaoUtils.getSingleTon().getmDaoSession().getUnusefulEpcDao().deleteAll();
        GreenDaoUtils.getSingleTon().getmDaoSession().getTagInfoDao().deleteAll();
    }

    /**
     * 获得商品及标签数据
     */
    public void getGoodsAndTagHttp() {
        refresh();
        goodsAndTagThread = new Thread(new Runnable() {
            @Override
            public void run() {
                //子线程初始化一个looper对象
                Looper.prepare();
//                getGoodsLabel();
                getEpcRetrofitHttp();
                Looper.loop();
            }
        });
        goodsAndTagThread.start();
    }

    /**
     * 获取仓库列表
     */
    public void getWarehouseHttp() {
        handler.sendEmptyMessage(ON_LOADING);
        Map<String, String> params = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, ""));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID, 0));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.TOKEN, ""));
        builder.append("|");
        builder.append(0);
        builder.append("|");
        params.put("brandtoken", builder.toString());
        params.put("is_show", "1");
        RetrofitManager.getDefault().create(ApiServer.class).getWareHouse(RetrofitManager.getHeader(), params)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseListResult<WarehouseBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {

                    }

                    @Override
                    public void onNext(BaseListResult<WarehouseBean> result) {
                        Trace.e("WarehouseBean+++++++++ " + result.isSuccess());
                        if (result.isSuccess()) {
                            List<WarehouseBean> list = result.getData();
                            if (null == list || list.size() == 0) {
                                view.onWarehouseEmpty("暂无仓库列表");
                            } else {
                                //设置数据
                                view.onWarehouseSuccess(list);
                            }
                        } else {
                            Trace.e("StockWeanInfo+++++++++ " + result.getMsg());
                            view.onWarehouseError("网络异常");
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        view.onWarehouseError("网络异常");
                        Trace.e("StockWeanInfo+++++++++ " + e.getMessage());
                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }


    public void checkEpcCanTake(String tagIds) {
        Map<String, String> params = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, ""));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID, 0));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.TOKEN, ""));
        builder.append("|");
        builder.append(0);
        builder.append("|");
        params.put("brandtoken", builder.toString());
        params.put("tagid_list", tagIds);
        params.put("timeStamp", System.currentTimeMillis() / 1000 + "");//加时间戳参数
        params.put("sign", MD5Util.md5(params));//md5加密并加参数
        Trace.e("提交的参数： ： " + tagIds);
        RetrofitManager.getDefault().create(ApiServer.class)
                .checkEpcCanTake(RetrofitManager.getUrl(UrlInterface.checkEpcAllocationStatus, params),
                        RetrofitManager.getHeader(),
                        RetrofitManager.getNewParams(params))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<BaseListResult<EpcTagBean>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        compositeDisposable.add(d);
                    }

                    @Override
                    public void onNext(BaseListResult<EpcTagBean> result) {
                        Trace.e("列表数据： " + new Gson().toJson(result));
                        if (result.isSuccess()) {
                            if (null != result.getData() && result.getData().size() > 0) {
                                view.checkShowList(result.getList());
                            } else {
                                view.checkShowList(null);
                            }
                        } else {

                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Trace.e("wcj====" + e.getMessage());

                    }

                    @Override
                    public void onComplete() {

                    }
                });
    }

    /**
     * 获取仓库列表
     */
    public void getAllEpcTagIds() {
        handler.sendEmptyMessage(ON_LOADING);
        Map<String, String> params = new HashMap<>();
        StringBuilder builder = new StringBuilder();
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.BRAND_ID, ""));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getInt(PreferenceUtil.USER_ID, 0));
        builder.append("|");
        builder.append(PreferenceUtil.getInstance().getString(PreferenceUtil.TOKEN, ""));
        builder.append("|");
        builder.append(0);
        builder.append("|");
        params.put("brandtoken", builder.toString());
        params.put("timeStamp", System.currentTimeMillis() / 1000 + "");//加时间戳参数
        params.put("sign", MD5Util.md5(params));//md5加密并加参数
        Map<String, String> header = RetrofitManager.getHeader();
        header.put("gzip_type", "1");
        RetrofitManager.getDefault().create(ApiServer.class).getAllEpcTagIds(header, params)
                .enqueue(new Callback<ResponseBody>() {
                    @Override
                    public void onResponse(Call<ResponseBody> call, Response<ResponseBody> response) {
                        if (null != response && null != response.body()) {
                            if (null != response.body().source() && response.isSuccessful()) {
                                //获得response中的body的字节数组
                                try {
                                    //通过UTF-8解压缩成json字符串
                                    String json = GZIPUtils.uncompressToString(response.body().source().readByteArray(), GZIPUtils.GZIP_ENCODE_UTF_8);
                                    //将字符串转换成定义好的数据类型
                                    final JSONObject jsonObject = new JSONObject(json);
                                    if (jsonObject.getBoolean("success")) {
                                        JSONArray array = jsonObject.getJSONArray("data");
                                        if (array != null && array.length() > 0) {
                                            view.checkShowList(GsonFactory.getObjectList(array.toString(), EpcTagBean.class));
                                        } else {
                                            view.checkShowList(null);
                                        }
                                    } else {
                                        view.checkShowList(null);
                                    }
                                } catch (Exception e) {

                                }
                            }
                        }
                    }

                    @Override
                    public void onFailure(Call<ResponseBody> call, Throwable t) {

                    }
                });

    }


}
